package com.tcs.test.netty.client.breakChannelListen;

import com.tcs.test.netty.client.NettyClient;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit;

public class BreakChannelFuture implements ChannelFutureListener {

    private final Logger logger = LoggerFactory.getLogger(BreakChannelFuture.class);

    private  int count = 0;

    private BreakChannelFuture(){};

    private static BreakChannelFuture breakChannelFuture = new BreakChannelFuture();

    public static BreakChannelFuture getBreakChannelFuture() {
        if (null == breakChannelFuture) {
            breakChannelFuture = new BreakChannelFuture();
        }
        return breakChannelFuture;
    }

    @Override
    public void operationComplete(ChannelFuture future) throws Exception {
        if (future.isSuccess()) {
            ByteBuf byteBuf = Unpooled.copiedBuffer("hello", Charset.defaultCharset());
            ChannelFuture channelFuture = future.channel().writeAndFlush(byteBuf);
            logger.info("哈哈");
        } else {
            reConection();
        }
    }

    private void reConection() {
        try {
            Bootstrap bootstrap = NettyClient.getBootstrap();
            ChannelFuture channelFuture = bootstrap.connect();
            channelFuture.addListener(BreakChannelFuture.getBreakChannelFuture());
            channelFuture.channel().eventLoop().schedule(new Runnable() {
                @Override
                public void run() {
                    logger.info("info 链接失败!重连中!!! ");
                    reConection();
                }
            },5L, TimeUnit.SECONDS);
        } catch (Exception e) {
            logger.error("" , e);
        }

    }
}
